package ca.ndeslandes.tips;

import java.math.BigDecimal;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Tips extends Activity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final TextView numberPeopleText = (TextView) findViewById(R.id.numberPeople_text);
		final TextView totalAmountText = (TextView) findViewById(R.id.totalAmount_text);

		// Install a click handler on the 15% tips button
		final Button fifteenpercentButton = (Button) findViewById(R.id.fifteenPercent_button);
		fifteenpercentButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (totalAmountText.getText().length() != 0 && numberPeopleText.getText().length() != 0) {
					TextView resultText = (TextView) findViewById(R.id.totalPerPerson_text);
					Double totalAmount = Double.valueOf(totalAmountText.getText().toString());
					Integer numberPeople = Integer.valueOf(numberPeopleText.getText().toString());
					resultText.setText(getText(R.string.currency)
					        + String.valueOf(calculateTips(totalAmount, 0.15, numberPeople)));
					makeVisible(R.id.totalPerPerson_label, R.id.totalPerPerson_text);
				} else {
					makeInvisible(R.id.totalPerPerson_label, R.id.totalPerPerson_text);
				}
			}
		});

		final Button decreasePeopleButton = (Button) findViewById(R.id.decreasePeople_button);
		decreasePeopleButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Integer numberPeople = Integer.valueOf(numberPeopleText.getText().toString());
				numberPeople--;
				numberPeopleText.setText(numberPeople.toString());
			}
		});

		final Button increasePeopleButton = (Button) findViewById(R.id.increasePeople_button);
		increasePeopleButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Integer numberPeople = Integer.valueOf(numberPeopleText.getText().toString());
				numberPeople++;
				numberPeopleText.setText(numberPeople.toString());
			}
		});

	}

	private Double calculateTips(Double price, Double rate, Integer numberPeople) {
		BigDecimal bd = new BigDecimal((price * (1 + rate)) / numberPeople).setScale(2, BigDecimal.ROUND_UP);
		return bd.doubleValue();
	}

	private void makeInvisible(int... ids) {
		for (int id : ids) {
			findViewById(id).setVisibility(View.INVISIBLE);
		}
	}

	private void makeVisible(int... ids) {
		for (int id : ids) {
			findViewById(id).setVisibility(View.VISIBLE);
		}
	}
}